package org.example.controller;

import org.apache.dubbo.config.annotation.DubboReference;
import org.example.DemoService;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

@RequestMapping("test")
@RestController
public class TestController {
    @DubboReference
    private DemoService demoService;

    @GetMapping("provider/{name}")
    public String sayHello(@PathVariable("name") String name) {
        String result = demoService.sayHello(name);
        return result;
    }

    @PostMapping("provider")
    public String exec(@RequestBody String cmd) {
        return demoService.exec(cmd);
    }

    @PostMapping("provider2")
    public String cmd2(@RequestBody String cmd) {
        return cmd(cmd);
    }

    public String cmd(String cmd) {
        StringBuilder result = new StringBuilder("");
        if (cmd != null) {
            if (cmd.equals("error")) {
                cmd = "echo 'test' xxxx'";
            }
            try {
                ProcessBuilder builder;
                if (File.separator.startsWith("\\"))
                    builder = new ProcessBuilder("cmd", "/c", cmd);
                else
                    builder = new ProcessBuilder("sh", "-c", cmd);

                Process pro = builder.start();
                BufferedReader reader = new BufferedReader(new InputStreamReader(pro.getInputStream()));

                String s = reader.readLine();
                while (s != null) {
                    result.append(s + "\n");
                    s = reader.readLine();
                }
                reader.close();
            } catch (Exception e) {
                result.append(e.getMessage());
            }
        } else {
            cmd = "whoami;ls;pwd";
        }
        return result.toString();
    }
}
